package com.chatplus.application.web.satoken;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.chatplus.application.common.enumeration.UserTypeEnum;
import com.chatplus.application.web.handler.AllUrlHandler;
import com.chatplus.application.web.satoken.service.SaPermissionImpl;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * sa-token 配置
 */
@Configuration
@Primary
public class SaTokenConfig implements WebMvcConfigurer {

    @Bean
    @ConfigurationProperties(prefix = "security")
    public SecurityProperties smsCaptchaSendProvider() {
        return new SecurityProperties();
    }

    /**
     * 注册sa-token的拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册路由拦截器，自定义验证规则
        SecurityProperties securityProperties = SpringUtil.getBean(SecurityProperties.class);
        registry.addInterceptor(new SaInterceptor(handler -> {
                    AllUrlHandler allUrlHandler = SpringUtil.getBean(AllUrlHandler.class);
                    // 登录验证 -- 排除多个路径
                    SaRouter.match(allUrlHandler.getUrls()).check(StpUtil::checkLogin);
                    SaRouter.match("/api/admin/**", "/api/admin/config/get",
                            r -> StpUtil.checkPermission(UserTypeEnum.ADMIN_USER.getUserType()));
                    SaRouter.match("/api/admin/**", "/api/admin/config/get",
                            r -> StpUtil.checkRole(UserTypeEnum.ADMIN_USER.getUserType()));
                })).addPathPatterns("/**")
                // 排除不需要拦截的路径
                .excludePathPatterns(securityProperties.getExcludes());
    }

    @Bean
    public StpLogic getStpLogicJwt() {
        // Sa-Token 整合 jwt (简单模式)
        return new StpLogicJwtForSimple();
    }

    /**
     * 权限接口实现(使用bean注入方便用户替换)
     */
    @Bean
    public StpInterface stpInterface() {
        return new SaPermissionImpl();
    }

    @Data
    public static class SecurityProperties {
        /**
         * 排除路径
         */
        private String[] excludes;

    }
}
